package com.caishi.lkx.distribution.service.impl;



import com.caishi.lkx.common.unionpay.sdk.HttpsUtil;
import com.caishi.lkx.distribution.properties.WeixinModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class WeChatSignService {

    // 替换为你的公众号 appid 和 appsecret
    private  final String APPID ;
    private  final String APPSECRET ;

    // 缓存 jsapi_ticket 及其过期时间（7200秒）
    private static String cachedJsApiTicket = null;
    private static long ticketExpiresTime = 0;
    @Autowired
    public WeChatSignService(WeixinModel weixinModel){
        this.APPID= weixinModel.getFwAppid();
        this.APPSECRET = weixinModel.getFwAppSecret();
    }

    /**
     * 获取签名配置数据
     */
    public Map<String, Object> getWxConfigSign(String url) throws Exception {
        String jsApiTicket = getJsApiTicket();

        String nonceStr = generateNonceStr();
        long timestamp = System.currentTimeMillis() / 1000;

        // 拼接签名字符串
        String stringToSign = "jsapi_ticket=" + jsApiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;

        // SHA-1 加密
        String signature = sha1(stringToSign);

        Map<String, Object> result = new HashMap<>();
        result.put("appId", APPID);
        result.put("timestamp", timestamp);
        result.put("nonceStr", nonceStr);
        result.put("signature", signature);

        return result;
    }

    /**
     * 获取 jsapi_ticket
     */
    private String getJsApiTicket() throws Exception {
        if (cachedJsApiTicket != null && System.currentTimeMillis() < ticketExpiresTime) {
            return cachedJsApiTicket;
        }

        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";

        Map<String, Object> response = HttpsUtil.getWithUrl(url);
        if (response.containsKey("ticket")) {
            cachedJsApiTicket = (String) response.get("ticket");
            ticketExpiresTime = System.currentTimeMillis() + ((Integer) response.get("expires_in")) * 1000L;
            return cachedJsApiTicket;
        } else {
            throw new RuntimeException("获取 jsapi_ticket 失败：" + response.toString());
        }
    }

    /**
     * 获取 access_token
     */
    private String getAccessToken() throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + APPID + "&secret=" + APPSECRET;

        Map<String, Object> response = HttpsUtil.getWithUrl(url);
        if (response.containsKey("access_token")) {
            return (String) response.get("access_token");
        } else {
            throw new RuntimeException("获取 access_token 失败：" + response.toString());
        }
    }

    /**
     * 生成 16 位随机字符串
     */
    private String generateNonceStr() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder res = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            res.append(chars.charAt(random.nextInt(chars.length())));
        }
        return res.toString();
    }

    /**
     * SHA-1 加密方法
     */
    private String sha1(String input) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        byte[] hash = digest.digest(input.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();

        for (byte b : hash) {
            String shaHex = Integer.toHexString(b & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }

        return hexString.toString();
    }
}
